package com.jiutong.meipengdai.views.dialog;

import android.annotation.SuppressLint;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.jiutong.meipengdai.R;
import com.jiutong.meipengdai.common.Constants;
import com.jiutong.meipengdai.http.RetrofitHandle;
import com.jiutong.meipengdai.utils.SpConfig;
import com.jiutong.meipengdai.utils.ToastUtil;

/**
 */

@SuppressLint("ValidFragment")
public class ChangeUrlDialog extends DialogFragment {

    private EditText etUrl;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //去掉dialog的标题，需要在setContentView()之前
        this.getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        Window window = this.getDialog().getWindow();
        //去掉dialog默认的padding
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //设置dialog的位置在底部
        lp.gravity = Gravity.CENTER;
        //设置dialog的动画
        lp.windowAnimations = R.style.dialog_animation_fade;
        window.setAttributes(lp);
        window.setBackgroundDrawable(new ColorDrawable());
        final View view = inflater.inflate(R.layout.dialog_change_url, null);
        etUrl = (EditText) view.findViewById(R.id.et_url);
        etUrl.setHint(TextUtils.isEmpty(SpConfig.getInstance().getString(Constants.BASEURL_TEST)) ? RetrofitHandle.getInstance().BASE_URL : SpConfig.getInstance().getString(Constants.BASEURL_TEST));
        TextView tvOk = (TextView) view.findViewById(R.id.tv_ok);

        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(etUrl.getText().toString().trim())) {
                    ToastUtil.shortToast(getContext(), "请输入url");
                } else {
                    SpConfig.getInstance().putString(Constants.BASEURL_TEST, "http://" + etUrl.getText().toString().trim());
                    ToastUtil.shortToast(getContext(), "请在后台杀死进程后重启");
                    dismiss();
                }
            }
        });

        TextView tvCancel = (TextView) view.findViewById(R.id.tv_cancel);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        return view;
    }
}
